using System;
using System.Collections.Generic;
using System.Text;
using ACS.Compiler.Tables;
using ACS.Compiler.Tables.Modes;
using ACS.Compiler.Tree.Interfaces;
using ACS.Compiler.Util;
using ACS.Compiler.Synthes;

namespace ACS.Compiler.Tree.Impl
{
    public class While : Statement
    {
        public override Statements StatementType
        {
            get { return Statements.While; }
        }

        private IExpression _condition;
        private Block _body;

        public override void MatchSelect(Select select)
        {
            MatchExpression(select);
        }

        public override void MatchExpression(IExpression expression)
        {
            _condition = expression;
        }

        public override void MatchCall(Call call)
        {
            MatchExpression(call);
        }

        public override void MatchBlock(Block block)
        {
            _body = block;
        }

        public override void MatchIdent(Ident ident)
        {
            MatchExpression(ident);
        }

        public IExpression Condition
        {
            get { return _condition; }
        }

        public Block Body
        {
            get { return _body; }
        }

        public override void Resolve(string ns, DataTable localData)
        {
            Mode condMode = _condition.ModeResolveExpression(ns, localData, null);
            if (condMode != null && ModesTable.Castable(condMode, BoolMode.Instance))
            {
                Body.Resolve(ns, localData);
            } else
            {
                Logger.Instance.TraceError("wrong \"while\" condition mode");
            }
        }

        public override void Format()
        {
            Formatter.Current.Format(
                String.Format("while ({0})", _condition.ToDeclareString()));
            Body.Format();
        }
    }
}
